import { isString, isBoolean, isMyObject, isNumber } from "./infer-types";
/**
 * 将number类型转换成哈希值
 * @param val number类型
 */
export function numberToHash(val: number): number {
  return val >>> 0;
}
/**
 * 将boolean类型转换成哈希值
 * @param val boolean类型
 */
export function booleanToHash(val: boolean): number {
  return val ? 1231 : 1237;
}
/**
 * 将string类型转换成哈希值
 * @param val string类型
 */
export function stringToHash(val: string): number {
  let hash = 0;
  const len = val.length;
  if (len == 0) return hash;
  for (let i = 0; i < len; i++) {
    const char = val.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash = hash & hash;
  }
  return hash;
}
/**
 * 将任意类型转换成哈希值
 * @param obj 任意类型
 */
export function hashCode(obj: unknown): number {
  if (isString(obj)) return stringToHash(obj);
  else if (isBoolean(obj)) return booleanToHash(obj);
  else if (isMyObject(obj)) return obj.hash;
  else if (isNumber(obj)) return numberToHash(obj);
  else return stringToHash(JSON.stringify(obj));
}
